package com.ikingtech.platform.service.datasource.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.base.model.PageResult;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.datasource.model.DatasourceSchemaQueryParam;
import com.ikingtech.framework.sdk.datasource.model.DatasourceQueryParamDTO;
import com.ikingtech.framework.sdk.datasource.model.enums.DatasourceSchemaTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.datasource.entity.DatasourceDO;
import com.ikingtech.platform.service.datasource.mapper.DatasourceMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DatasourceService extends ServiceImpl<DatasourceMapper, DatasourceDO> {

    private final Map<String, DataSource> dataSourceMap = new HashMap<>();

    public PageResult<DatasourceDO> listPage(DatasourceQueryParamDTO queryParam) {
        return PageResult.build(this.page(new Page<>(queryParam.getPage(), queryParam.getRows()), Wrappers.<DatasourceDO>lambdaQuery()
                .like(Tools.Str.isNotBlank(queryParam.getName()), DatasourceDO::getName, queryParam.getName())
                .eq(Tools.Str.isNotBlank(queryParam.getType()), DatasourceDO::getType, queryParam.getType())
                .like(Tools.Str.isNotBlank(queryParam.getIp()), DatasourceDO::getJdbcUrl, queryParam.getIp())
                .like(Tools.Str.isNotBlank(queryParam.getPort()), DatasourceDO::getJdbcUrl, queryParam.getPort())
                .like(Tools.Str.isNotBlank(queryParam.getSchemaName()), DatasourceDO::getJdbcUrl, queryParam.getSchemaName())
                .like(Tools.Str.isNotBlank(queryParam.getRemark()), DatasourceDO::getRemark, queryParam.getRemark())
                .eq(null != queryParam.getCreateTime(), DatasourceDO::getCreateTime, queryParam.getCreateTime())
                .eq(null != queryParam.getUpdateTime(), DatasourceDO::getUpdateTime, queryParam.getUpdateTime())));
    }

    public List<DatasourceDO> listByTenantCode(String tenantCode) {
        return this.list(Wrappers.<DatasourceDO>lambdaQuery().eq(DatasourceDO::getTenantCode, tenantCode));
    }

    public List<Map<String, Object>> execute(DatasourceDO entity, String sql) {
        return this.execute(DatasourceSchemaTypeEnum.valueOf(entity.getType()), entity.getJdbcUrl(), entity.getUsername(), entity.getPassword(), sql);
    }

    public List<Map<String, Object>> execute(DatasourceSchemaQueryParam queryParam, String sql) {
        return this.execute(queryParam.getType(), queryParam.getJdbcUrl(), queryParam.getUsername(), queryParam.getPassword(), sql);
    }

    public List<Map<String, Object>> execute(DatasourceSchemaTypeEnum type, String jdbcUrl, String username, String password, String sql) {
        List<Map<String, Object>> result = new ArrayList<>();
        DataSource dataSource = this.dataSourceMap.get(jdbcUrl);
        if (null == dataSource) {
            dataSource = this.createDatasource(type, jdbcUrl, username, password);
            this.dataSourceMap.put(jdbcUrl, dataSource);
        }
        try (Connection connection = dataSource.getConnection()) {
            Statement statement = connection.createStatement();
            ResultSet executeResult = statement.executeQuery(sql);
            ResultSetMetaData resultMetaData = executeResult.getMetaData();
            while (executeResult.next()) {
                Map<String, Object> columnResult = new HashMap<>();
                for (int i = 1; i <= resultMetaData.getColumnCount(); i++) {
                    columnResult.put(resultMetaData.getColumnName(i), executeResult.getObject(i));
                }
                result.add(columnResult);
            }
            statement.close();
            return result;
        } catch (Exception e) {
            log.error("service-datasource error: {}", ExceptionUtils.getStackTrace(e));
            throw new FrameworkException("datasourceExecuteException");
        }
    }

    private DataSource createDatasource(DatasourceSchemaTypeEnum databaseType, String jdbcUrl, String username, String password) {
        try (DruidDataSource datasource = new DruidDataSource()) {
            datasource.setDriverClassName(databaseType.driverClassName);
            datasource.setUrl(jdbcUrl);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setBreakAfterAcquireFailure(true);
            return datasource;
        } catch (Exception e) {
            throw new FrameworkException("datasourceCreateFail");
        }
    }

    public void removeByTenantCode(String tenantCode) {
        this.remove(Wrappers.<DatasourceDO>lambdaQuery().eq(DatasourceDO::getTenantCode, tenantCode));
    }

    public boolean nameExist(String name, String tenantCode) {
        return this.baseMapper.exists(Wrappers.<DatasourceDO>lambdaQuery().isNotNull(DatasourceDO::getId).eq(DatasourceDO::getName, name).eq(DatasourceDO::getTenantCode, tenantCode));
    }

    public boolean nameExist(String id, String name, String tenantCode) {
        return this.baseMapper.exists(Wrappers.<DatasourceDO>lambdaQuery().ne(DatasourceDO::getId, id).eq(DatasourceDO::getName, name).eq(DatasourceDO::getTenantCode, tenantCode));
    }

    public boolean exist(String id) {
        return this.baseMapper.exists(Wrappers.<DatasourceDO>lambdaQuery().eq(DatasourceDO::getId, id));
    }

    public DatasourceDO getDefaultDatasource() {
        return this.getOne(Wrappers.<DatasourceDO>lambdaQuery().eq(DatasourceDO::getDefaultDatasource, true));
    }
}
